﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Windows.Threading;
using System.Reflection;
using System.IO;

namespace AutoPowerSwitch
{
    public partial class MainWindow
    {
        #region Global Variables
        int instanceCount;
        List<string> typeList;
        List<string> appList = new List<string>();
        List<int> hourList, minuteList, secondList;
        int hour, minute, second;
        DispatcherTimer timer;
        bool isShutDown, isRestart, isLogOff, isLock, isStandBy, isHiberante;
        string commandType, applicationList, osCommandType;

        private System.Windows.Forms.NotifyIcon TrayNotify;
        private System.Windows.Forms.ContextMenuStrip ctxTrayMenu;
        private bool isAppExiting = false;
        #endregion

        #region Constructor
        public MainWindow()
        {
            InitializeComponent();
            txtNote.Text = "Note : \rSelect A Command if it is Operating System Or Add Applications if it is Application.";
            btnRemoveApplication.IsEnabled = false;
            typeList = new List<string> { "Application", "Operating System" };
            hourList = new List<int> {  00, 01, 02, 03, 04, 05, 06, 07, 08, 09, 
                                        10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 
                                        20, 21, 22, 23 };
            minuteList = new List<int> {  00, 01, 02, 03, 04, 05, 06, 07, 08, 09, 
                                        10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 
                                        20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
                                        30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
                                        40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
                                        50, 51, 52, 53, 54, 55, 56, 57, 58, 59 };
            secondList = minuteList;
            cmbType.ItemsSource = typeList;
            cmbHour.ItemsSource = hourList;
            cmbMinute.ItemsSource = minuteList;
            cmbSeconds.ItemsSource = secondList;

            timer = new DispatcherTimer();
            timer.Tick += new EventHandler(timer_Tick);

            if (File.Exists(Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments) + "\\" + "PowerConfig.txt"))
            {
                ReadFromFile();
                if (commandType.Equals("Application"))
                {
                    cmbType.SelectedIndex = 0;
                    string[] words = applicationList.Split('|');
                    for (int i = 0; i < words.Length-1; i++)
                    {
                        appList.Add(words[i]);
                    }
                    lbApplications.ItemsSource = appList;
                    SetTimerValues();
                }
                else
                {
                    cmbType.SelectedIndex = 1;
                    if (osCommandType != "False")
                    {
                        switch (osCommandType)
                        {
                            case "Shut Down":
                                radioShutDown.IsChecked = true;
                                break;
                            case "Restart":
                                radioRestart.IsChecked = true;
                                break;
                            case "Log Off":
                                radioLogOff.IsChecked = true;
                                break;
                            case "Lock":
                                radioLock.IsChecked = true;
                                break;
                            case "Stand By":
                                radioStandBy.IsChecked = true;
                                break;
                            case "Hibernate":
                                radioHibernate.IsChecked = true;
                                break;
                            default:
                                break;
                        }
                    }
                    SetTimerValues();
                }
            }
            else
            {
                cmbType.SelectedIndex = 1;
                cmbHour.SelectedIndex = 0;
                cmbMinute.SelectedIndex = 0;
                cmbSeconds.SelectedIndex = 0;
            }
        }
        #endregion

        #region SetTimerValues()
        private void SetTimerValues()
        {
            foreach (int item in cmbHour.Items)
            {
                if (item == hour)
                {
                    cmbHour.SelectedItem = item;
                    break;
                }
            }

            foreach (int item in cmbMinute.Items)
            {
                if (item == minute)
                {
                    cmbMinute.SelectedItem = item;
                    break;
                }
            }

            foreach (int item in cmbSeconds.Items)
            {
                if (item == second)
                {
                    cmbSeconds.SelectedItem = item;
                    break;
                }
            }
        }
        #endregion

        #region ComboBox-SelectionChanged-cmbType
        private void cmbType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cmbType.SelectedIndex != -1)
            {
                if (cmbType.SelectedItem.Equals("Application"))
                {
                    expApp.IsExpanded = true;
                }
                else
                {
                    expOS.IsExpanded = true;
                }
            }
        }
        #endregion

        #region Expander-Expanded-expOs, expApp
        private void Expander_Expanded(object sender, RoutedEventArgs e)
        {
            Expander expander = sender as Expander;
            string control = expander.Header.ToString();
            if (control.Equals("Operating System"))
            {
                expOS.IsExpanded = true;
                expApp.IsExpanded = false;
            }
            else
            {
                expOS.IsExpanded = false;
                expApp.IsExpanded = true;
            }
        } 
        #endregion

        #region Expander-Collapsed-expOs, expApp
        private void Expander_Collapsed(object sender, RoutedEventArgs e)
        {
            Expander expander = sender as Expander;
            string control = expander.Header.ToString();
            if (control.Equals("Operating System"))
            {
                expOS.IsExpanded = false;
                expApp.IsExpanded = true;
            }
            else
            {
                expOS.IsExpanded = true;
                expApp.IsExpanded = false;
            }
        } 
        #endregion

        #region Button-Click-btnStartStop
        private void btnStartStop_Click(object sender, RoutedEventArgs e)
        {
            if (btnStartStop.Content.Equals("Start"))
            {
                btnStartStop.Content = "Stop";
                ControlsIsEnabled(false);
                StartTimer();
                timer.Interval = TimeSpan.FromMilliseconds(200);
                timer.Start();
                instanceCount = 1;
                SaveAndMinimizeToTray();
            }
            else
            {
                btnStartStop.Content = "Start";
                ControlsIsEnabled(true);
                timer.Stop();
            }
        }
        #endregion

        #region Button-Click-btnNow
        private void btnNow_Click(object sender, RoutedEventArgs e)
        {
            if (cmbType.SelectedIndex != -1)
            {
                if (cmbType.SelectedIndex == 1)
                {
                    PerformOperatingSystem();
                }
                else
                {
                    PerformApplication();
                }
            }
        }
        #endregion

        #region Button-Click-btnAddApplication
        private void btnAddApplication_Click(object sender, RoutedEventArgs e)
        {
            List<string> tempList = new List<string>();
            AddExeDialog();
            tempList = appList.Distinct().ToList();
            lbApplications.ItemsSource = tempList;
        }
        #endregion

        #region Button-Click-btnRemoveApplication
        private void btnRemoveApplication_Click(object sender, RoutedEventArgs e)
        {
            if (lbApplications.SelectedIndex != -1)
            {
                foreach (string item in appList)
                {
                    if (lbApplications.SelectedItem.Equals(item))
                    {
                        appList.Remove(item);
                        if (appList.Count == 0)
                        {
                            lbApplications.ItemsSource = null;
                        }
                        else
                        {
                            lbApplications.ItemsSource = appList;
                        }
                        lbApplications.SelectedIndex = -1;
                        break;
                    }
                }
            }
        }
        #endregion

        #region ListBox-SelectionChanged-lbApplications
        private void lbApplications_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (lbApplications.SelectedIndex != -1)
            {
                btnRemoveApplication.IsEnabled = true;
            }
            else
            {
                btnRemoveApplication.IsEnabled = false;
            }
        }
        #endregion

        #region Image-MouseLeftButtonDown-ShutDown,Restart,LogOff,Lock,Hibernate,StandBy
        private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Image img = sender as Image;
            string tag = img.Tag.ToString();
            switch (tag)
            {
                case "Shut Down":
                    radioShutDown.IsChecked = true;
                    break;
                case "Restart":
                    radioRestart.IsChecked = true;
                    break;
                case "Log Off":
                    radioLogOff.IsChecked = true;
                    break;
                case "Lock":
                    radioLock.IsChecked = true;
                    break;
                case "Stand By":
                    radioStandBy.IsChecked = true;
                    break;
                case "Hibernate":
                    radioHibernate.IsChecked = true;
                    break;
                default:
                    break;
            }
        } 
        #endregion

        #region Image-MouseLeftButtonDown-imgInfo
        private void imgInfo_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Window about = new About();
            about.ShowDialog();
        }
        #endregion

        #region ControlsIsEnabled(bool)
        private void ControlsIsEnabled(bool bValue)
        {
            cmbType.IsEnabled = bValue;
            expOS.IsEnabled = bValue;
            expApp.IsEnabled = bValue;
            cmbHour.IsEnabled = bValue;
            cmbMinute.IsEnabled = bValue;
            cmbSeconds.IsEnabled = bValue;
        }
        #endregion

        #region Timer-Tick-timer
        void timer_Tick(object sender, EventArgs e)
        {
            DateTime userTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, hour, minute, second, 0, DateTimeKind.Local);
            DateTime currentTime = DateTime.Now;
            string userTimeString = userTime.ToLongTimeString();
            string currentTimeString = currentTime.ToLongTimeString();
            if (currentTimeString.Equals(userTimeString))
            {
                if (cmbType.SelectedIndex != -1)
                {
                    if (cmbType.SelectedIndex == 1)
                    {
                        PerformOperatingSystem();
                    }
                    else
                    {
                        PerformApplication();
                    }
                }
            }
        }
        #endregion

        #region StartTimer()
        private void StartTimer()
        {
            if (cmbHour.SelectedIndex != -1 && cmbMinute.SelectedIndex != -1 && cmbSeconds.SelectedIndex != -1)
            {
                hour = Convert.ToInt32(cmbHour.SelectedItem);
                minute = Convert.ToInt32(cmbMinute.SelectedItem);
                second = Convert.ToInt32(cmbSeconds.SelectedItem);
            }
        }
        #endregion

        #region PerformOperatingSystem()
        private void PerformOperatingSystem()
        {
            isShutDown = (bool)radioShutDown.IsChecked;
            isRestart = (bool)radioRestart.IsChecked;
            isLogOff = (bool)radioLogOff.IsChecked;
            isLock = (bool)radioLock.IsChecked;
            isStandBy = (bool)radioStandBy.IsChecked;
            isHiberante = (bool)radioHibernate.IsChecked;

            if (isShutDown)
            {
                Process.Start("shutdown", "-s -f -t 0");
            }
            else if (isRestart)
            {
                Process.Start("shutdown", "-r -f -t 0");
            }
            else if (isLogOff)
            {
                Process.Start("logoff");
            }
            else if (isLock)
            {
                Process.Start(@"C:\WINDOWS\system32\rundll32.exe", "user32.dll,LockWorkStation");
            }
            else if (isStandBy)
            {
                System.Windows.Forms.Application.SetSuspendState(PowerState.Suspend, true, true);
            }
            else if (isHiberante)
            {
                System.Windows.Forms.Application.SetSuspendState(PowerState.Hibernate, true, true);
            }
        }

        [DllImport("user32.dll")]
        public static extern void LockWorkStation();
        #endregion

        #region PerformApplication()
        private void PerformApplication()
        {
            Process[] processArray = Process.GetProcesses();
            foreach (Process process in processArray)
	        {
                foreach (string item in lbApplications.Items)
                {
                    string tempProcess = process.ToString();
                    if (tempProcess.Equals("System.Diagnostics.Process (" + item.ToLower() + ")"))
                    {
                        process.Kill();
                    }
                } 
	        }
            
        } 
        #endregion

        #region AddExeDialog()
        private void AddExeDialog()
        {
            System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog();
            ofd.Filter = "Application files (*.exe)|*.exe";
            DialogResult result = ofd.ShowDialog();

            if (result == System.Windows.Forms.DialogResult.OK)
            {
                string filename = ofd.SafeFileName;
                string[] words = filename.Split('.');
                appList.Add(words[0]);
            }
        }
        #endregion

        #region SaveAndMinimizeToTray()
        private void SaveAndMinimizeToTray()
        {
            WriteToFile();

            TrayNotify = new System.Windows.Forms.NotifyIcon();
            TrayNotify.Icon = new System.Drawing.Icon(Assembly.GetExecutingAssembly().Location + "..\\..\\Application.ico");
            TrayNotify.Visible = true;
            ctxTrayMenu = new System.Windows.Forms.ContextMenuStrip();

            System.Windows.Forms.ToolStripMenuItem mnuExit = new System.Windows.Forms.ToolStripMenuItem();
            mnuExit.Text = "Exit";
            mnuExit.Click += new EventHandler(mnuExit_Click);

            System.Windows.Forms.ToolStripMenuItem mnuSettings = new System.Windows.Forms.ToolStripMenuItem();
            mnuSettings.Text = "Settings";
            mnuSettings.Click += new EventHandler(mnuSettings_Click);

            System.Windows.Forms.ToolStripMenuItem mnuStop = new System.Windows.Forms.ToolStripMenuItem();
            if (btnStartStop.Content.Equals("Stop"))
            {
                mnuStop.Text = "Stop";
            }
            else
            {
                mnuStop.Text = "Start";
            }
            mnuStop.Click += new EventHandler(mnuStop_Click);

            ctxTrayMenu.Items.Add(mnuStop);
            ctxTrayMenu.Items.Add("-");
            ctxTrayMenu.Items.Add("-");
            ctxTrayMenu.Items.Add(mnuSettings);
            ctxTrayMenu.Items.Add("-");
            ctxTrayMenu.Items.Add("-");
            ctxTrayMenu.Items.Add(mnuExit);

            TrayNotify.DoubleClick += new EventHandler(TrayNotify_DoubleClick);

            TrayNotify.ContextMenuStrip = ctxTrayMenu;

            this.WindowState = WindowState.Minimized;
            this.ShowInTaskbar = false;

            TrayNotify.BalloonTipIcon = System.Windows.Forms.ToolTipIcon.Info;
            TrayNotify.BalloonTipTitle = "Auto Power Switch";
            TrayNotify.BalloonTipText = "Your Settings have been Saved.";
            TrayNotify.ShowBalloonTip(200);
        }
        #endregion

        #region Menu-Click-mnuStop
        void mnuStop_Click(object sender, EventArgs e)
        {
            if (btnStartStop.Content.Equals("Start"))
            {
                btnStartStop.Content = "Stop";
                ControlsIsEnabled(false);
                StartTimer();
                timer.Interval = TimeSpan.FromMilliseconds(200);
                timer.Start();
            }
            else
            {
                btnStartStop.Content = "Start";
                ControlsIsEnabled(true);
                timer.Stop();
            }
        }
        #endregion

        #region Menu Click [System Tray Exit]
        void mnuExit_Click(object sender, EventArgs e)
        {
            isAppExiting = true;
            this.Close();
            TrayNotify.Visible = false;
        }
        #endregion

        #region Menu Click [System Tray Settings]
        void mnuSettings_Click(object sender, EventArgs e)
        {
            isAppExiting = false;
            this.Show();
            this.ShowInTaskbar = true;
            this.WindowState = WindowState.Normal;
            TrayNotify.Visible = false;
        }
        #endregion

        #region TrayIcon DoubleClick [System Tray Icon]
        void TrayNotify_DoubleClick(object sender, EventArgs e)
        {
            isAppExiting = false;
            this.Show();
            this.ShowInTaskbar = true;
            this.WindowState = WindowState.Normal;
            TrayNotify.Visible = false;
        }
        #endregion

        #region Window StateChanged [MainWindow]
        private void GlassWindow_StateChanged(object sender, EventArgs e)
        {
            if (instanceCount != 1)
            {
                if (this.WindowState == WindowState.Minimized)
                {
                    SaveAndMinimizeToTray();
                }
            }
            instanceCount = 0;
        }
        #endregion

        #region WriteToFile()
        private void WriteToFile()
        {
            if (cmbType.SelectedIndex != -1)
            {
                #region Write for Application
                if (cmbType.SelectedIndex == 0)
                {
                    string appList = string.Empty;
                    if (lbApplications.ItemsSource != null)
                    {
                        foreach (string item in lbApplications.Items)
                        {
                            appList += item + "|";
                        }
                    }
                    StreamWriter SW;
                    string configPath = Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
                    SW = File.CreateText(configPath + "\\" + "PowerConfig.txt");
                    SW.WriteLine(
                        "Application" +
                        ";" + appList +
                        ";" + cmbHour.SelectedItem.ToString() +
                        ";" + cmbMinute.SelectedItem.ToString() +
                        ";" + cmbSeconds.SelectedItem.ToString() + ";");
                    SW.Close();
                } 
                #endregion

                #region Write for Operating System
                else
                {
                    #region Command Type
                    string commandType = string.Empty;
                    if ((bool)radioShutDown.IsChecked)
                    {
                        commandType = "Shut Down";
                    }
                    else if ((bool)radioRestart.IsChecked)
                    {
                        commandType = "Restart";
                    }
                    else if ((bool)radioLogOff.IsChecked)
                    {
                        commandType = "Log Off";
                    }
                    else if ((bool)radioLock.IsChecked)
                    {
                        commandType = "Lock";
                    }
                    else if ((bool)radioStandBy.IsChecked)
                    {
                        commandType = "Stand By";
                    }
                    else if ((bool)radioHibernate.IsChecked)
                    {
                        commandType = "Hibernate";
                    }
                    else
                    {
                        commandType = "False";
                    }
                    #endregion

                    StreamWriter SW;
                    string configPath = Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
                    SW = File.CreateText(configPath + "\\" + "PowerConfig.txt");
                    SW.WriteLine(
                        "Operating System" +
                        ";" + commandType +
                        ";" + cmbHour.SelectedItem.ToString() +
                        ";" + cmbMinute.SelectedItem.ToString() +
                        ";" + cmbSeconds.SelectedItem.ToString() + ";");
                    SW.Close();
                } 
                #endregion
            }
            
        }
        #endregion

        #region ReadFromFile()
        private void ReadFromFile()
        {
            string configPath = Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);

            StreamReader SR;
            SR = File.OpenText(configPath + "\\" + "PowerConfig.txt");
            string fileContent = SR.ReadLine();
            string[] words = fileContent.Split(';');
            commandType = words[0];
            if (commandType.Equals("Application"))
            {
                applicationList = words[1];
            }
            else
            {
                osCommandType = words[1];
            }
            hour = Convert.ToInt32(words[2]); ;
            minute = Convert.ToInt32(words[3]);
            second = Convert.ToInt32(words[4]);
            
            SR.Close();
        }
        #endregion
    }
}
